package com.simple.action.fee;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.simple.po.EmpEmployee;
import com.simple.po.FeeDetail;
import com.simple.po.FeeReport;
import com.simple.po.FeeRetention;
import com.simple.po.FeeWrittenOff;
import com.simple.service.fee.FeeService;
import com.simple.service.fee.FeeWrittenOffService;
import com.xunj.action.common.AbstractAction;
import com.xunj.core.ParaUnit;
import com.xunj.core.SessionBean;
import com.xunj.po.SysCodeDict;
import com.xunj.service.system.UserService;
import com.xunj.util.Common;

/**
 * 费用登记
 * @author 王瑾
 *
 */
public class FeeDetailAction extends AbstractAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = -365972686059686745L;
	private FeeDetail feeDetail; //费用登记
	private FeeReport feeReport; //费用登记


	
	/**
	 * 查询费用信息
	 * @return
	 * @throws Exception
	 */
	public String listFeeDetail() throws Exception
	{
		ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
		if(feeDetail==null)
		{
			paralist.add(new ParaUnit("state", "在用", ParaUnit.EQ));
			feeDetail = new FeeDetail();
			feeDetail.setState("在用");
		}
		paralist.add(new ParaUnit("createDate", ParaUnit.DESC,ParaUnit.ORDER));
		
		if(POST())
		{
			paralist.add(new ParaUnit("state", feeDetail.getState(), ParaUnit.EQ));
			if(!feeDetail.getAreaId().equals(""))
				paralist.add(new ParaUnit("areaId", feeDetail.getAreaId(), ParaUnit.EQ));
			if(!feeDetail.getAreaDeptId().equals(""))
				paralist.add(new ParaUnit("areaDeptId", feeDetail.getAreaDeptId(), ParaUnit.EQ));
			String feeDateFrom = request.getParameter("feeDateFrom");
			String feeDateTo = request.getParameter("feeDateTo");
			if(!feeDateFrom.equals(""))
			{
				paralist.add(new ParaUnit("feeDate",Common.newDate(feeDateFrom+" 00:00:00", "yyyy-MM-dd"), ParaUnit.GE));
				request.setAttribute("feeDateFrom", feeDateFrom);
			}
			if(!feeDateTo.equals(""))
			{
				paralist.add(new ParaUnit("feeDate",Common.newDate(feeDateTo+" 23:59:59", "yyyy-MM-dd"), ParaUnit.LE));
				request.setAttribute("feeDateTo", feeDateTo);
			}
			if(!feeDetail.getFeeTypeId().equals(""))
				paralist.add(new ParaUnit("feeTypeId", feeDetail.getFeeTypeId(), ParaUnit.EQ));
			if(!feeDetail.getFeeTarget().equals(""))
				paralist.add(new ParaUnit("feeTarget", feeDetail.getFeeTarget(), ParaUnit.EQ));
			if(!feeDetail.getTargetName().equals(""))
				paralist.add(new ParaUnit("targetName", feeDetail.getTargetName(), ParaUnit.LIKE));
			
		}
		
		List list = dao.criteriaByPage(FeeDetail.class, paralist);
		List reportIds = new ArrayList();
		if(feeDetail.getState().equals("上报"))
		{
			for(int i=0;i<list.size();i++)
			{
				FeeDetail fd = (FeeDetail) list.get(i);
				if(!reportIds.contains(fd.getFeeReportId()))
					reportIds.add(fd.getFeeReportId());
			}
			String reportId = "";
			if(!reportIds.isEmpty())
			{
				for(int i=0;i<reportIds.size();i++)
					reportId+="'"+reportIds.get(i)+"',";
			}
			if(reportId.length()>0)
			{
				reportId = reportId.substring(0, reportId.length()-1);
				String hql = " from FeeReport where feeReportId in ("+reportId+")";
				List feeReportList = dao.findAll(hql);
				request.setAttribute("feeReportList", feeReportList);
			}
		}
		request.setAttribute("datalist", list);
		return toJsp("/jsp/fee/fee_detail/lst_fee_detail.jsp");
	}
	
	/**
	 * 添加费用信息
	 * @return
	 * @throws Exception
	 */
	public String addFeeDetail() throws Exception
	{
		UserService us = new UserService(dao);
		//提交类型，save直接保存、saveAndAdd保存后复制添加
		String submitType = request.getParameter("submitType");
		//调用页面来源，费用填报或费用核销
		String from = request.getParameter("from");
		if(POST())
		{
			HttpServletRequest request = ServletActionContext.getRequest();
			SessionBean sessionBean  = SessionBean.getSessionBean(request);
			feeDetail.setFeeId(UUID.randomUUID().toString());
			feeDetail.setState("在用");
			feeDetail.setCreateUserId(sessionBean.getUserId());
			feeDetail.setCreateUserName(sessionBean.getUserName());
			feeDetail.setUpdateState("否");
			if(from!=null&&from.equals("writtenOff"))
			{
				feeDetail.setFeeReportId(request.getParameter("feeReportId"));
				feeDetail.setIsAddState("加调");
				feeDetail.setState("上报");
			}
			dao.save(feeDetail);
			FeeWrittenOff feeWrittenOff = new FeeWrittenOff();
			feeWrittenOff.setFeeId(feeDetail.getFeeId());
			feeWrittenOff.setBillAmountWrittenOff(feeDetail.getBillAmount());
			feeWrittenOff.setBillCountWrittenOff(feeDetail.getBillCount());
			feeWrittenOff.setCertificateAmountWrittenOff(feeDetail.getCertificateAmount());
			feeWrittenOff.setCertificateCountWrittenOff(feeDetail.getCertificateCount());
			dao.save(feeWrittenOff);
			//加调项目更新上报汇总值
			if(from!=null&&from.equals("writtenOff"))
			{
				FeeWrittenOffService wos = new FeeWrittenOffService(dao);
				wos.totalFeeReport(request.getParameter("feeReportId"));
			}
			if("save".equals(submitType))
				this.Alert_Close("保存成功", "ok");
			else
			{
				String[] userRoles = {"cwzg"};
				List userList = us.getUserByUserRole(null, userRoles);
				request.setAttribute("userList", userList);
				return toJsp("/jsp/fee/fee_detail/add_fee_detail.jsp");
			}
			return toMessage();
		}
		else
		{
			String[] userRoles = {"cwzg"};
			List userList = us.getUserByUserRole(null, userRoles);
			request.setAttribute("userList", userList);
			
			//页面调用来源，writtenOff代表费用核销中的加调项目
			if(from!=null&&from.equals("writtenOff"))
			{
				String feeReportId = request.getParameter("feeReportId");
				ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
				paralist.add(new ParaUnit("feeReportId", feeReportId, ParaUnit.EQ));
				//查询一条费用明细数据
				List feeDetailList = dao.criteriaCustomRow(FeeDetail.class, paralist, 1);

				FeeDetail fd = (FeeDetail) feeDetailList.get(0);
				feeDetail = new FeeDetail();
				feeDetail.setAreaId(fd.getAreaId());
				feeDetail.setAreaName(fd.getAreaName());
				feeDetail.setAreaDeptId(fd.getAreaDeptId());
				feeDetail.setAreaDeptName(fd.getAreaDeptName());
				
			}
			else
			{
				feeDetail = new FeeDetail();
				feeDetail.setFeeDate(new Date());
			}
			return toJsp("/jsp/fee/fee_detail/add_fee_detail.jsp");
		}
	}
	/**
	 * 修改费用信息
	 * @return
	 * @throws Exception
	 */
	public String updateFeeDetail() throws Exception
	{
		UserService us = new UserService(dao);
		//提交类型，save直接保存、saveAndAdd保存后复制添加
		String submitType = request.getParameter("submitType");
		if(POST())
		{
			dao.update(feeDetail);
			FeeWrittenOff feeWrittenOff = (FeeWrittenOff) dao.findOne(FeeWrittenOff.class, feeDetail.getFeeId());
			if(feeDetail.getState().equals("核销"))
			{
				feeWrittenOff.setBillAmountWrittenOff(Common.sum(feeDetail.getBillAmount(),
						feeWrittenOff.getBillAmountAdjust(),
						feeWrittenOff.getBillAmountLeaveReview()==null?0d:feeWrittenOff.getBillAmountLeaveReview()*-1,
						feeWrittenOff.getBillAmountLeaveReviewEarly(),
						feeWrittenOff.getBillAmountRetruned()==null?0d:feeWrittenOff.getBillAmountRetruned()*-1));
				feeWrittenOff.setBillCountWrittenOff(Common.sum(feeDetail.getBillCount(),
						feeWrittenOff.getBillCountAdjust(),
						feeWrittenOff.getBillCountLeaveReview()==null?0:feeWrittenOff.getBillCountLeaveReview()*-1,
								feeWrittenOff.getBillCountLeaveReviewEarly(),
								feeWrittenOff.getBillCountRetruned()==null?0:feeWrittenOff.getBillCountRetruned()*-1));
				feeWrittenOff.setCertificateAmountWrittenOff(Common.sum(feeDetail.getCertificateAmount(),
						feeWrittenOff.getCertificateAmountAdjust(),
						feeWrittenOff.getCertificateAmountLeaveReview()==null?0d:feeWrittenOff.getCertificateAmountLeaveReview()*-1,
								feeWrittenOff.getCertificateAmountLeaveReviewEarly(),
								feeWrittenOff.getCertificateAmountRetruned()==null?0d:feeWrittenOff.getCertificateAmountRetruned()*-1));
				feeWrittenOff.setCertificateCountWrittenOff(Common.sum(feeDetail.getCertificateCount(),
						feeWrittenOff.getCertificateCountAdjust(),
						feeWrittenOff.getCertificateCountLeaveReview()==null?0:feeWrittenOff.getCertificateCountLeaveReview()*-1,
								feeWrittenOff.getCertificateCountLeaveReviewEarly(),
								feeWrittenOff.getCertificateCountRetruned()==null?0:feeWrittenOff.getCertificateCountRetruned()*-1));
			
				
			}
			else
			{
				feeWrittenOff.setBillAmountWrittenOff(feeDetail.getBillAmount());
				feeWrittenOff.setBillCountWrittenOff(feeDetail.getBillCount());
				feeWrittenOff.setCertificateAmountWrittenOff(feeDetail.getCertificateAmount());
				feeWrittenOff.setCertificateCountWrittenOff(feeDetail.getCertificateCount());
			}
			dao.update(feeWrittenOff);
			String from = request.getParameter("from");
			//加调项目更新上报汇总值
			if(from!=null&&from.equals("writtenOff"))
			{
				FeeWrittenOffService wos = new FeeWrittenOffService(dao);
				wos.totalFeeReport(feeDetail.getFeeReportId());
			}
			
			if("save".equals(submitType))
				this.Alert_Close("保存成功", "ok");
			else
			{
				String[] userRoles = {"cwzg"};
				List userList = us.getUserByUserRole(null, userRoles);
				request.setAttribute("userList", userList);
				return toJsp("/jsp/fee/fee_detail/add_fee_detail.jsp");
			}
			return toMessage();
		}
		else
		{
			String feeId = request.getParameter("feeId");
			feeDetail = (FeeDetail)dao.findOne(FeeDetail.class, feeId);
			String[] userRoles = {"cwzg"};
			List userList = us.getUserByUserRole(null, userRoles);
			request.setAttribute("userList", userList);
			return toJsp("/jsp/fee/fee_detail/update_fee_detail.jsp");
		}
	}
	/**
	 * 删除费用信息
	 * @return
	 * @throws Exception
	 */
	public String deleteFeeDetail() throws Exception
	{
		String feeId = request.getParameter("feeId");
		feeDetail = (FeeDetail)dao.findOne(FeeDetail.class, feeId);
		feeDetail.setState("删除");
		this.Alert_Close("删除成功", "ok");
		return toMessage();
	}
	/**
	 * 动态显示费用对象数据
	 * @return
	 * @throws Exception
	 */
	public String showFeeTargetFeeDetail() throws Exception
	{
		String feeTarget = request.getParameter("feeTarget");
		String data = "<option value=\"\">请选择</option>";
		if("地区人员".equals(feeTarget)){
			String areaId = request.getParameter("areaId");
			ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
			
			paralist.add(new ParaUnit("state", "在用", ParaUnit.EQ));
			paralist.add(new ParaUnit("employeeOrder", ParaUnit.ASC,ParaUnit.ORDER));
			if(areaId!=null)
				paralist.add(new ParaUnit("areaId", areaId, ParaUnit.EQ));
			List list = dao.criteriaQuery(EmpEmployee.class, paralist);
			
			for(int i=0;i<list.size();i++)
			{
				EmpEmployee emp = (EmpEmployee) list.get(i);
				data+="<option value=\""+emp.getEmployeeId()+"\">"+emp.getEmployeeName()+"</option>";
			}
			
		}else if("地区办事处".equals(feeTarget))
		{
			List codeList = (List) this.getServletContext().getAttribute("CodeDict");
			
			for(int i=0;i<codeList.size();i++)
			{
				SysCodeDict code = (SysCodeDict) codeList.get(i);
				if(code.getKindId().equals("006"))
				{
					data+="<option value=\""+code.getCodeId()+"\">"+code.getCodeName()+"</option>";
				}
			}
		}else if("销售分线".equals(feeTarget)){
			List codeList = (List) this.getServletContext().getAttribute("CodeDict");
			
			for(int i=0;i<codeList.size();i++)
			{
				SysCodeDict code = (SysCodeDict) codeList.get(i);
				if(code.getKindId().equals("003"))
				{
					data+="<option value=\""+code.getCodeId()+"\">"+code.getCodeName()+"</option>";
				}
			}
		}
		request.setAttribute("data", data);
		return toResult();
	}

	/**
	 * 查看费用信息
	 * @return
	 * @throws Exception
	 */
	public String showFeeDetail() throws Exception
	{
		String feeId = request.getParameter("feeId");
		feeDetail = (FeeDetail)dao.findOne(FeeDetail.class, feeId);
		if(feeDetail.getState().equals("核销完毕"))
		{
			FeeWrittenOff feeWrittenOff = (FeeWrittenOff) dao.findOne(FeeWrittenOff.class, feeId);
			request.setAttribute("feeWrittenOff", feeWrittenOff);
		}
		return toJsp("/jsp/fee/fee_detail/show_fee_detail.jsp");
	}
	
	
	/**
	 * 费用上报
	 * @return
	 * @throws Exception
	 */
	public String addReportFeeDetail() throws Exception
	{
		if(POST())
		{
			HttpServletRequest request = ServletActionContext.getRequest();
			SessionBean sessionBean  = SessionBean.getSessionBean(request);
			feeReport.setFeeReportId(UUID.randomUUID().toString());
			feeReport.setCreateUserId(sessionBean.getUserId());
			feeReport.setCreateUserName(sessionBean.getUserName());
			feeReport.setCreateDate(new Date());
			
			FeeService fs = new FeeService(dao);
			String newCode=fs.getFeeReportCode();
			feeReport.setFeeReportCode(newCode);
			
			int maxDay = 0;
			int day = 1;
	
	        Calendar calendar = Calendar.getInstance();
	        /**
	         * 实例化日历各个字段,这里的day为实例化使用
	         */
	        calendar.set(Integer.parseInt(feeReport.getFeeReportYear()),Integer.parseInt(feeReport.getFeeReportMonth()) - 1,day);
	        /**
	         * Calendar.Date:表示一个月中的某天
	         * calendar.getActualMaximum(int field):返回指定日历字段可能拥有的最大值
	         */
	        maxDay = calendar.getActualMaximum(Calendar.DATE);
			
	        
	        String whereCondition = "f.areaId='"+feeReport.getAreaId()+"' and " +
						"f.areaDeptId='"+feeReport.getAreaDeptId()+"' and " +
						"f.state<>'上报' and state<>'删除' and f.feeReportId is null and " +
						"f.feeDate between '"+feeReport.getFeeReportYear()+"-"+feeReport.getFeeReportMonth()+"-01 00:00:00' and "+
						" '"+feeReport.getFeeReportYear()+"-"+feeReport.getFeeReportMonth()+"-"+maxDay+" 23:59:59' ";
	        String countHql = "select count(*) from FeeDetail f where "+whereCondition;
	        int count = dao.findRowCount(countHql);
	        
	        if(count!=0)
	        {
				String hql = "update FeeDetail f set f.feeReportId='"+feeReport.getFeeReportId()+"'," +
						"f.state = '上报' where "+whereCondition;
				String sumHql = "select new Map(sum(f.billAmount) as billAmount," +
				"sum(f.certificateAmount) as certificateAmount," +
				"sum(f.billCount) as billCount," +
				"sum(f.certificateCount) as certificateCount," +
				"sum(fw.billAmountWrittenOff) as billAmountWrittenOff," +
				"sum(fw.certificateAmountWrittenOff) as certificateAmountWrittenOff," +
				"sum(fw.billCountWrittenOff) as billCountWrittenOff," +
				"sum(fw.certificateCountWrittenOff) as certificateCountWrittenOff" +
				") from FeeDetail f,FeeWrittenOff fw where f.feeId=fw.feeId and "+whereCondition;
				
				List feeTotalList = dao.findAll(sumHql);
				if(!feeTotalList.isEmpty())
				{
					Map map = (Map) feeTotalList.get(0);
					feeReport.setReportBillAmount((Double)map.get("billAmount"));
					if(map.get("billCount")!=null)
						feeReport.setReportBillCount(Integer.parseInt(map.get("billCount")+""));
					feeReport.setReportCertificateAmount((Double)map.get("certificateAmount"));
					if(map.get("certificateCount")!=null)
						feeReport.setReportCertificateCount(Integer.parseInt(map.get("certificateCount")+""));
					feeReport.setBillAmountTol((Double)map.get("billAmountWrittenOff"));
					if(map.get("billCountWrittenOff")!=null)
						feeReport.setBillCountTol(Integer.parseInt(map.get("billCountWrittenOff")+""));
					feeReport.setCertificateAmountTol((Double)map.get("certificateAmountWrittenOff"));
					if(map.get("certificateCountWrittenOff")!=null)
						feeReport.setCertificateCountTol(Integer.parseInt(map.get("certificateCountWrittenOff")+""));
				}
				
				dao.save(feeReport);
				dao.bulkUpdate(hql);
				hql = "update FeeWrittenOff f set f.feeReportId='"+feeReport.getFeeReportId() +"'" +
						"where f.feeId in (select feeId from FeeDetail where feeReportId='"+feeReport.getFeeReportId() +"')";
				dao.bulkUpdate(hql);
				
				this.Alert_Close("保存成功", "ok");
	        }
	        else
	        	this.Alert_Close("所选上报条件无费用信息！", "err");
			return toMessage();
		}
		else{
			FeeService fs = new FeeService(dao);
			String newCode=fs.getFeeReportCode();
			
			feeReport = new FeeReport();
			feeReport.setFeeReportCode(newCode);
			return toJsp("/jsp/fee/fee_detail/add_fee_report.jsp");
		}
	}
	/**
	 * 费用汇总上报检测合计费用金额功能
	 * @return
	 * @throws Exception
	 */
	public String listCheckReportFeeDetail() throws Exception
	{

		int maxDay = 0;
		int day = 1;
		
		Calendar calendar = Calendar.getInstance();
		/**
		 * 实例化日历各个字段,这里的day为实例化使用
		 */
		calendar.set(Integer.parseInt(feeReport.getFeeReportYear()),Integer.parseInt(feeReport.getFeeReportMonth()) - 1,day);
		/**
		 * Calendar.Date:表示一个月中的某天
		 * calendar.getActualMaximum(int field):返回指定日历字段可能拥有的最大值
		 */
		maxDay = calendar.getActualMaximum(Calendar.DATE);
		
		
		String whereCondition = "f.areaId='"+feeReport.getAreaId()+"' and " +
		"f.areaDeptId='"+feeReport.getAreaDeptId()+"' and " +
		"f.state<>'上报' and state<>'删除' and f.feeReportId is null and " +
		"f.feeDate between '"+feeReport.getFeeReportYear()+"-"+feeReport.getFeeReportMonth()+"-01 00:00:00' and "+
		" '"+feeReport.getFeeReportYear()+"-"+feeReport.getFeeReportMonth()+"-"+maxDay+" 23:59:59' ";
		String countHql = "select count(*) from FeeDetail f where "+whereCondition;
		int count = dao.findRowCount(countHql);
		
		if(count!=0)
		{
			String sumHql = "select new Map(sum(f.billAmount) as billAmount,sum(f.certificateAmount) as certificateAmount) from FeeDetail f where "+whereCondition;
			
			List feeTotalList = dao.findAll(sumHql);
			if(!feeTotalList.isEmpty())
			{
				request.setAttribute("feeDetailTolState", "yes");
				request.setAttribute("feeTotal", feeTotalList.get(0));
			}
			
		}
		else
			request.setAttribute("feeDetailTolState", "no");
		return toJsp("/jsp/fee/fee_detail/show_total_fee_report.jsp");

	}
	/**
	 * 查询费用信息
	 * @return
	 * @throws Exception
	 */
	public String listReportFeeDetail() throws Exception
	{
		ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();

		paralist.add(new ParaUnit("createDate", ParaUnit.DESC,ParaUnit.ORDER));
		
		if(POST())
		{
			if(!feeReport.getAreaId().equals(""))
				paralist.add(new ParaUnit("areaId", feeReport.getAreaId(), ParaUnit.EQ));
			if(!feeReport.getAreaDeptId().equals(""))
				paralist.add(new ParaUnit("areaDeptId", feeReport.getAreaDeptId(), ParaUnit.EQ));
			
			if(!feeReport.getFeeReportYear().equals(""))
				paralist.add(new ParaUnit("feeReportYear", feeReport.getFeeReportYear(), ParaUnit.EQ));
			if(!feeReport.getFeeReportMonth().equals(""))
				paralist.add(new ParaUnit("feeReportMonth", feeReport.getFeeReportMonth(), ParaUnit.EQ));
			if(!feeReport.getReportState().equals(""))
				paralist.add(new ParaUnit("reportState", feeReport.getReportState(), ParaUnit.EQ));
			if(!feeReport.getFeeReportCode().equals(""))
				paralist.add(new ParaUnit("feeReportCode", feeReport.getFeeReportCode(), ParaUnit.LIKE));
			
			
		}
		
		List list = dao.criteriaByPage(FeeReport.class, paralist);

		request.setAttribute("datalist", list);
		return toJsp("/jsp/fee/fee_detail/lst_fee_report.jsp");
	}
	/**
	 * 修改费用上报信息
	 * @return
	 * @throws Exception
	 */
	public String updateReportFeeDetail() throws Exception
	{
		if(POST())
		{
			FeeReport fr = (FeeReport) dao.findOne(FeeReport.class, feeReport.getFeeReportId());
			fr.setFeeReportCode(feeReport.getFeeReportCode());
			fr.setEndDate(feeReport.getEndDate());
			this.Alert_GoUrl("保存成功！", "listReportFeeDetail.do");
			return toMessage();
		}
		else
		{
			String feeReportId = request.getParameter("feeReportId");
			
			feeReport = (FeeReport)dao.findOne(FeeReport.class, feeReportId);
			
			//是否从修改处重新调用方法刷新费用明细数据，是则重新计算费用合计
			String fromType = request.getParameter("fromType");
			if("fromEdit".equals(fromType))
			{
				String sumHql = "select new Map(sum(f.billAmount) as billAmount," +
				"sum(f.certificateAmount) as certificateAmount," +
				"sum(f.billCount) as billCount," +
				"sum(f.certificateCount) as certificateCount" +
				") from FeeDetail f where feeReportId='"+feeReportId+"'";
		
				List feeTotalList = dao.findAll(sumHql);
				if(!feeTotalList.isEmpty())
				{
					Map map = (Map) feeTotalList.get(0);
					feeReport.setBillAmountTol((Double)map.get("billAmount"));
					feeReport.setBillCountTol((Long)map.get("billCount")==0?0:Integer.parseInt(map.get("billCount")+""));
					feeReport.setCertificateAmountTol((Double)map.get("certificateAmount"));
					feeReport.setCertificateCountTol((Long)map.get("certificateCount")==0?0:Integer.parseInt(map.get("certificateCount")+""));
				}
			}
			
			
			ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
			paralist.add(new ParaUnit("feeReportId", feeReportId, ParaUnit.EQ));
			paralist.add(new ParaUnit("createDate", ParaUnit.DESC,ParaUnit.ORDER));
			List list = dao.criteriaQuery(FeeDetail.class, paralist);
	
			request.setAttribute("datalist", list);
			return toJsp("/jsp/fee/fee_detail/update_fee_report.jsp");
		}
	}
	/**
	 * 删除费用上报信息
	 * @return
	 * @throws Exception
	 */
	public String deleteReportFeeDetail() throws Exception
	{
		String feeReportId = request.getParameter("feeReportId");
		String hql = "update FeeDetail f set f.feeReportId = null ,f.state='在用' where feeReportId = '"+feeReportId+"'";
		dao.bulkUpdate(hql);
		hql = "delete from FeeReport where feeReportId = '"+feeReportId+"'";
		dao.bulkUpdate(hql);
		this.Alert_Close("删除成功", "ok");
		return toMessage();
	}
	/**
	 * 上报费用上报信息
	 * @return
	 * @throws Exception
	 */
	public String reportFeeDetail() throws Exception
	{
		String feeReportId = request.getParameter("feeReportId");
		feeReport = (FeeReport)dao.findOne(FeeReport.class, feeReportId);
		feeReport.setReportState("已上报");
		
		ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
		paralist.add(new ParaUnit("feeReportId", feeReportId, ParaUnit.EQ));
		paralist.add(new ParaUnit("createDate", ParaUnit.DESC,ParaUnit.ORDER));
		List feeDetailList = dao.criteriaQuery(FeeDetail.class, paralist);
		FeeService fs = new FeeService(dao);
		this.Alert_Close("上报成功", "ok");
		return toMessage();
	}
	/**
	 * 从费用上报信息中移除费用明细信息
	 * @return
	 * @throws Exception
	 */
	public String removeFeeDetail() throws Exception
	{
		String feeId = request.getParameter("feeId");
		feeDetail = (FeeDetail)dao.findOne(FeeDetail.class, feeId);
		String feeReportId = feeDetail.getFeeReportId();
		feeDetail.setState("在用");
		feeDetail.setFeeReportId(null);
		//从费用核销处调整移除
		String from = request.getParameter("from");
		if(from!=null&&from.equals("writtenOff"))
		{
			FeeWrittenOff feeWrittenOff = (FeeWrittenOff) dao.findOne(FeeWrittenOff.class, feeId);
			feeWrittenOff.setBillAmountWrittenOff(feeDetail.getBillAmount());
			feeWrittenOff.setBillCountWrittenOff(feeDetail.getBillCount());
			feeWrittenOff.setCertificateAmountWrittenOff(feeDetail.getCertificateAmount());
			feeWrittenOff.setCertificateCountWrittenOff(feeDetail.getCertificateCount());
			
			FeeRetention feeRetention = (FeeRetention) dao.findOne(FeeRetention.class, feeDetail.getTargetId());
		
			
			//对象留审额=留审总额-本次留审调整额+前期留审调整额
			feeRetention.setBillAmountLeaveReview(Common.sum(feeRetention.getBillAmountLeaveReview(),
					(feeWrittenOff.getBillAmountWrittenOff()==null?0d:feeWrittenOff.getBillAmountWrittenOff())*-1,
					feeWrittenOff.getBillAmountLeaveReviewEarly()));
			feeRetention.setBillCountLeaveReview(Common.sum(feeRetention.getBillCountLeaveReview(),
					(feeWrittenOff.getBillCountWrittenOff()==null?0:feeWrittenOff.getBillCountWrittenOff())*-1,
					feeWrittenOff.getBillCountLeaveReviewEarly()));
			feeRetention.setCertificateAmountLeaveReview(Common.sum(feeRetention.getCertificateAmountLeaveReview(),
					(feeWrittenOff.getCertificateAmountWrittenOff()==null?0d:feeWrittenOff.getCertificateAmountWrittenOff())*-1,
					feeWrittenOff.getCertificateAmountLeaveReviewEarly()));
			feeRetention.setCertificateCountLeaveReview(Common.sum(feeRetention.getCertificateCountLeaveReview(),
					(feeWrittenOff.getCertificateCountWrittenOff()==null?0:feeWrittenOff.getCertificateCountWrittenOff())*-1,
					feeWrittenOff.getCertificateCountLeaveReviewEarly()));
			
			
			dao.update(feeWrittenOff);
			dao.update(feeRetention);
			FeeWrittenOffService wos = new FeeWrittenOffService(dao);
			wos.totalFeeReport(feeReportId);
		}
		
		this.Alert_Close("数据移除成功", "ok");
		return toMessage();
	}
	/**
	 * 选择添加费用信息进行上报
	 * @return
	 * @throws Exception
	 */
	public String selectFeeDetail() throws Exception
	{
		feeReport = (FeeReport)dao.findOne(FeeReport.class, feeReport.getFeeReportId());
		
		ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
		paralist.add(new ParaUnit("areaId", feeReport.getAreaId(), ParaUnit.EQ));
		paralist.add(new ParaUnit("areaDeptId", feeReport.getAreaDeptId(), ParaUnit.EQ));
		paralist.add(new ParaUnit("state","在用", ParaUnit.EQ));
		paralist.add(new ParaUnit("createDate", ParaUnit.DESC,ParaUnit.ORDER));
		
		if(POST())
		{
			String feeDateFrom = request.getParameter("feeDateFrom");
			String feeDateTo = request.getParameter("feeDateTo");
			if(!feeDateFrom.equals(""))
			{
				paralist.add(new ParaUnit("feeDate",Common.newDate(feeDateFrom+" 00:00:00", "yyyy-MM-dd"), ParaUnit.GE));
				request.setAttribute("feeDateFrom", feeDateFrom);
			}
			if(!feeDateTo.equals(""))
			{
				paralist.add(new ParaUnit("feeDate",Common.newDate(feeDateTo+" 23:59:59", "yyyy-MM-dd"), ParaUnit.LE));
				request.setAttribute("feeDateTo", feeDateTo);
			}
			if(!feeDetail.getFeeTypeId().equals(""))
				paralist.add(new ParaUnit("feeTypeId", feeDetail.getFeeTypeId(), ParaUnit.EQ));
			if(!feeDetail.getFeeTarget().equals(""))
				paralist.add(new ParaUnit("feeTarget", feeDetail.getFeeTarget(), ParaUnit.EQ));
			if(!feeDetail.getTargetName().equals(""))
				paralist.add(new ParaUnit("targetName", feeDetail.getTargetName(), ParaUnit.EQ));
			
		}
		
		List list = dao.criteriaByPage(FeeDetail.class, paralist);

		request.setAttribute("datalist", list);
		return toJsp("/jsp/fee/fee_detail/select_fee_detail.jsp");
	}
	/**
	 * 查询显示同类费用信息
	 * @return
	 * @throws Exception
	 */
	public String listSameTypeFeeDetail() throws Exception
	{
		String condition = " and feeDetail.state<>'删除' and feeDetail.feeId<>'"+feeDetail.getFeeId()+"'";
		
		if(!feeDetail.getAreaId().equals(""))
			condition+=" and feeDetail.areaId='" + feeDetail.getAreaId()+"'";
		if(!feeDetail.getAreaDeptId().equals(""))
			condition+=" and feeDetail.areaDeptId='" + feeDetail.getAreaDeptId()+"'";
		if(!feeDetail.getFeeTypeId().equals(""))
			condition+=" and feeDetail.feeTypeId='" + feeDetail.getFeeTypeId()+"'";
		if(!feeDetail.getFeeTarget().equals(""))
			condition+=" and feeDetail.feeTarget='" + feeDetail.getFeeTarget()+"'";
		if(!feeDetail.getTargetId().equals(""))
			condition+=" and feeDetail.targetId='" + feeDetail.getTargetId()+"'";
		if(!feeDetail.getNote1().equals(""))
			condition+=" and feeDetail.note1 like '%" + feeDetail.getNote1()+"%'";
		if(!feeDetail.getNote2().equals(""))
			condition+=" and feeDetail.note1 like '%" + feeDetail.getNote2()+"%'";
		
		FeeService fs = new FeeService(dao);
		//费用核销明细
		
		List feeList = fs.queryFeeJoin("", condition, "order by feeDetail.createDate",true);
		request.setAttribute("datalist", feeList);
		return toJsp("/jsp/fee/fee_detail/lst_same_type_fee_detail.jsp");
	}
	/**
	 * 选择添加费用信息进行至上报数据
	 * @return
	 * @throws Exception
	 */
	public String addFeeToReportFeeDetail() throws Exception
	{
		String feeReportId = request.getParameter("feeReportId");
		String feeIds = request.getParameter("feeIds");
		
		feeReport = (FeeReport)dao.findOne(FeeReport.class, feeReportId);

		String instr = "";
		
		for(String s:feeIds.split(","))
		{
			instr+="'"+s+"',";
		}
		instr=instr.substring(0, instr.length()-1);

		String hql = "update FeeDetail f set f.feeReportId='"+feeReport.getFeeReportId()+"'," +
				"f.state='上报' where feeId in ("+instr+")";
		dao.bulkUpdate(hql);
		
		this.Alert_Close("保存成功", "ok");
		return toMessage();
	}
	/**
	 * 查看费用上报信息
	 * @return
	 * @throws Exception
	 */
	public String showReportFeeDetail() throws Exception
	{
		String feeReportId = request.getParameter("feeReportId");
		
		feeReport = (FeeReport)dao.findOne(FeeReport.class, feeReportId);
		
		ArrayList<ParaUnit> paralist = new ArrayList<ParaUnit>();
		paralist.add(new ParaUnit("feeReportId", feeReportId, ParaUnit.EQ));
		paralist.add(new ParaUnit("createDate", ParaUnit.DESC,ParaUnit.ORDER));
		List list = dao.criteriaQuery(FeeDetail.class, paralist);

		request.setAttribute("datalist", list);
		return toJsp("/jsp/fee/fee_detail/show_fee_report.jsp");
	}
	
	
	public FeeDetail getFeeDetail() {
		return feeDetail;
	}
	public void setFeeDetail(FeeDetail feeDetail) {
		this.feeDetail = feeDetail;
	}

	public FeeReport getFeeReport() {
		return feeReport;
	}

	public void setFeeReport(FeeReport feeReport) {
		this.feeReport = feeReport;
	}


}